import {PlusOutlined} from '@ant-design/icons';
import {Button, Tag, message, Input, Drawer, InputNumber, Select, Form, Modal} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import StockMouldForm from './components/StockMouldForm';
import {queryRule, updateRule, addRule, removeRule} from './service';
import {
  materialIntoWarehouse,
  queryWarehouseMaterial,
  queryWarehouseMaterialHistory,
  materialOutWarehouse,
  queryWarehouseMould, queryWarehouseMouldHistory, mouldIntoWarehouse, mouldDeleteWarehouse
} from "@/services/warehouse";

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [ioType, setIoType] = useState(1);
  const [selectedRecord, setSelectedRecord] = useState({});
  const [tabActiveKey, setTabActiveKey] = useState('1');
  const [addVisible, handleAddVisible] = useState(false);
  const [formTitle, setFormTitle] = useState('新增入库');
  const actionRef = useRef();
  const historyRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const { Option } = Select;
  const handleCreateModalVisible = (type, record)=>{
    setSelectedRecord(record)
    handleModalVisible(true)
    setIoType(type)
  }

  const deleteConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要删除名称为 【${record.mouldName} 】的模具？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        mouldDeleteWarehouse(record).then(res=>{
          if (res && res.status === '0') {
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }else {
            message.error(res.message)
          }
        });
      }
    });
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '仓库名称',
      dataIndex: 'warehouseName',
      valueType: 'input',
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={11} {...fieldProps} placeholder={'请输入仓库名称'}/>;
      }
    },
    {
      title: '模具编码',
      dataIndex: 'mouldCode',
      valueType: 'input',
    },
    {
      title: '模具名称',
      dataIndex: 'mouldName',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 10,
            message: '模具名称最大长度为10'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '模具名称是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={11} placeholder={'请输入模具名称'}/>;
      }
    },
    {
      title: '区域',
      dataIndex: 'warehouseArea',
      valueType: 'input',
    },
    {
      title: '货架',
      dataIndex: 'warehouseAreaShelf',
      valueType: 'input',
    },
    {
      title: '数量',
      dataIndex: 'num',
      sorter: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '数量是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <InputNumber min={1} defaultValue={1000} style={{width: '100%'}}/>;
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a  onClick={() => deleteConfig( record)}>
          删除
        </a>
      ],
    },
  ];

  const historyColumns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '分类',
      dataIndex: 'ioType',
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <Select>
            <Option value={-1}>全部</Option>
            <Option value={1}>入库</Option>
            <Option value={2}>删除</Option>
          </Select>
        );
      },
      render: (text)=>{
        return (<Tag color={text === 1? 'green': 'red'}>{text === 1? '入库': '删除'}</Tag>)
      }
    },
    {
      title: '仓库名称',
      dataIndex: 'warehouseName',
      valueType: 'input',
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={11} {...fieldProps} placeholder={'请输入仓库名称'}/>;
      }
    },
    {
      title: '模具名称',
      dataIndex: 'mouldName',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '模具名称是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={11} placeholder={'请输入模具名称'}/>;
      }
    },
    {
      title: '模具编码',
      dataIndex: 'mouldCode',
      valueType: 'input',
    },
    {
      title: '区域',
      dataIndex: 'warehouseArea',
      valueType: 'input',
      hideInSearch: true
    },
    {
      title: '货架',
      dataIndex: 'warehouseAreaShelf',
      valueType: 'input',
      hideInSearch: true
    },
    {
      title: '数量',
      dataIndex: 'num',
      sorter: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '数量是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <InputNumber min={1} defaultValue={1000} style={{width: '100%'}}/>;
      }
    },
    {
      title: '创建人',
      dataIndex: 'realName',
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => setRow(record)}>
          详情
        </a>
      ],
    },
  ];
  const onTabChange = (key)=>{
    setTabActiveKey(key)
  }

  const handleMaterialIn = async (fields) => {
    const hide = message.loading('正在入库');

    try {
      console.log(fields)
      await mouldIntoWarehouse(fields).then(res=>{
        if (res && res.status === '0') {
          if (actionRef.current) {
            actionRef.current.reload();
          }
          hide();
          message.success('入库成功');
        }
      });

      return true;
    } catch (error) {
      hide();
      message.error('入库失败请重试！');
      return false;
    }
  };

  const handleMaterialOut = async (fields) => {
    const hide = message.loading('正在出库');

    try {

      await materialOutWarehouse({...fields}).then(res=>{
        if (res && res.status === '0') {
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      });
      hide();
      message.success('出库成功');
      return true;
    } catch (error) {
      hide();
      message.error('出库失败请重试！');
      return false;
    }
  };

  const onSubmit = (values)=>{
    const success = ioType === 1? handleMaterialIn(values): handleMaterialOut(values)
    if(success) {
      handleModalVisible(false)
    }
  }

  return (
    <PageContainer
      tabActiveKey={tabActiveKey}
      onTabChange={onTabChange}
      content={createModalVisible? (ioType === 1?'入库申请':'出库申请') : ''}
      tabList={createModalVisible? null :
        [
          {
            tab: '库存',
            key: '1',
          },
          {
            tab: '操作履历',
            key: '2',
          }
      ]
      }
    >
      {tabActiveKey === '1' ? (
        <ProTable
          style={{display: createModalVisible? 'none': 'block'}}
          actionRef={actionRef}
          rowKey="key"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button type="primary" onClick={() => handleCreateModalVisible(1, {})}>
              <PlusOutlined/> 入库
            </Button>,
          ]}
          request={async (params, sorter, filter) => {
            const param = {...params, pageNum: params.current};
            const res = await queryWarehouseMould(param)
            return {
              data: res.result.records,
              success: true,
              total: res.result.total
            }
          }}
          columns={columns}
        />
      ): (<></>)}
      {
        createModalVisible? <StockMouldForm type={ioType} materialData={selectedRecord} onCancel={() => handleModalVisible(false)} visible={createModalVisible} onSubmit={onSubmit}></StockMouldForm>: <></>
      }

      {
        tabActiveKey === '2' ? (
          <ProTable
            style={{display: createModalVisible? 'none': 'block'}}
            actionRef={historyRef}
            rowKey="key"
            search={{
              labelWidth: 120,
            }}
            request={async (params, sorter, filter) => {
              params.ioType === -1? params.ioType = null: params.ioType = params.ioType
              const param = {...params, pageNum: params.current};
              const res = await queryWarehouseMouldHistory(param)
              return {
                data: res.result.records,
                success: true,
                total: res.result.total
              }
            }}
            columns={historyColumns}
          />
        ) : (<></>)
      }
      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.warehouseName && (
          <ProDescriptions
            column={2}
            title={row?.warehouseName}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.warehouseName,
            }}
            columns={historyColumns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
